<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import type { Rpm } from '@/api'
import { api } from '@/api'

const props = defineProps<{
  rpmInfo: Rpm
  cveId: string
  fixed: boolean
  hostId?: string
}>()

const { t } = useI18n()
const isDrawerVisible = ref(false)

const tableColumns = [
  {
    dataIndex: 'index',
    title: t('vul.cveDetail.index'),
  },
  {
    dataIndex: 'host_name',
    title: t('vul.hostName'),
  },
  {
    dataIndex: 'host_ip',
    title: 'IP',
  },
]

const tableData = ref<
  {
    host_ip: string
    host_name: string
  }[]
>([])

const hostId = ref()
const route = useRoute()

const isTableLoading = ref(false)

async function handleOpen() {
  isTableLoading.value = true
  const { cveId, rpmInfo, fixed } = props
  const [, res] = await api.getHostsWithPackage({
    cve_id: cveId,
    fixed,
    available_rpm: rpmInfo.available_rpm,
    installed_rpm: rpmInfo.installed_rpm,
    direction: 'asc',
    host_ids: hostId.value ? [hostId.value] : undefined,
  })
  if (res) {
    tableData.value = res.result.map((item, index) => ({
      index: index + 1,
      host_ip: item.host_ip,
      host_name: item.host_name,
    }))
  }
  isTableLoading.value = false
}

onMounted(() => {
  hostId.value = route.params.host_id as string || undefined
})
</script>

<template>
  <div class="affected-hosts">
    <div @click="isDrawerVisible = true">
      <slot name="trigger" />
    </div>
    <a-drawer
      v-model:open="isDrawerVisible"
      :width="600"
      :title="$t('vul.rpmList')"
      placement="right"
      :closable="false"
      destroy-on-close
      @after-open-change="handleOpen"
    >
      <a-table
        :columns="tableColumns"
        :data-source="tableData"
        :pagination="false"
        :loading="isTableLoading"
        bordered
      />
    </a-drawer>
  </div>
</template>
